// 即时通讯 

if (Meteor.isServer) {
  /**
   * 混合发布 chats 和 message
   * @param  {Boolean} conditions   find 的第一个参数
   * @param  {Object}  opt          find 的第二个参数， mongo 返回数组的限定条件
   * @return {Array}                cursor
   */
  Meteor.publishComposite('chats', function (conditions,opt) {
    if (! this.userId) return;
    var user = Meteor.users.findOne(this.userId,{_id: 0,'company_id':1});
    return {
      find: function () {
        var search;
        if(conditions && conditions instanceof Object){
          if(conditions._id){
            search = {'_id':conditions._id};
          }else if(conditions.is_notice && conditions.is_notice == true){
            search = { 'is_notice': true };
          }
        }else{
          search = {
            users : this.userId,
            users_quitted : {'$ne': this.userId},
          };
        }
        search.company_id = user.company_id;
        return Chats.find(search,opt);
      },
      children: [{
        find: function (chat) {
          return Messages.find({ chat_id: chat._id });
        }
      },{
        find: function (chat) {
          return Meteor.users.find({ _id: { $in: chat.users } }, { profile: 1 });
        }
      }]
    }
  });
}

Meteor.methods({
  // 新建聊天
  newChat(otherId) {
    if (! this.userId) {
      throw new Meteor.Error('not-logged-in',
        'Must be logged to create a chat.');
    }

    check(otherId, String);

    var otherUser = Meteor.users.findOne(otherId);
    if (! otherUser) {
      throw new Meteor.Error('user-not-exists','用户不存在');
    }

    var chat = {
      users: [this.userId, otherId],
      createdAt: new Date()
    };

    return Chats.insert(chat);
  },

  /**
   * 删除会话，实际并非删除，只是标记用户为已退出会话，该用户前端不再显示该会话
   * @param  {String} chatId 会话 ID
   */
  removeChat(chatId) {
    if (! this.userId) {
      throw new Meteor.Error('not-logged-in','请登录');
    }
    check(chatId, String);

    var chat = Chats.findOne(chatId);
    if (! chat || ! _.include(chat.users, this.userId)) {
      throw new Meteor.Error('chat-not-exists','会话不存在');
    }
    Chats.update({'_id':chatId}, { $push: { 'users_quitted':this.userId }});
    // return Chats.remove({ _id: chatId });
  },

  /**
   * 创建新消息
   * @param  {Object} data  新消息对象
   * @return {String}       被创建的新消息的 id
   */
  newMessage(data) {
    if (! this.userId) {
      throw new Meteor.Error('not-logged-in', '请登录.');
    }
    check(data, {
      content: String,
      user: {_id:String,name:String},
      chat_id: String,
      type: String
    });
    data.timestamp = new Date();
    data.user._id = this.userId;
    data.state = 1;
    var messageId = Messages.insert(data);
    var chatId = data.chat_id;
    delete data.chat_id;
    Chats.update({'_id':chatId}, { $set: { 'last_message': data,'users_quitted':[] }});
    return messageId;
  },
  /**
   * 更新会话名 TODO
   * @param  {[type]} name [description]
   * @return {[type]}      [description]
   */
  updateName(name) {
    if (! this.userId) {
      throw new Meteor.Error('not-logged-in','请登录');
    }

    check(name, String);
    if (name.length === 0) {
      throw Meteor.Error('name-required', 'Must provide user name');
    }

    return Meteor.users.update(this.userId, { $set: { 'profile.name': name } });
  }

});
// 演示数据
if (Chats.find().count() === 0) {
  var _chats = [{
      company_id:'1',
      avatar: 'https://pbs.twimg.com/profile_images/514549811765211136/9SgAuHeY.png',
      users:['1','2']
    },{
      company_id:'1',
      avatar: 'https://pbs.twimg.com/profile_images/514549811765211136/9SgAuHeY.png',
      users:['1','3']
    },{
      company_id:'1',
      avatar: 'https://pbs.twimg.com/profile_images/514549811765211136/9SgAuHeY.png',
      users:['2','4']
    },{
      company_id:'1',
      is_notice:true,
      avatar: 'https://pbs.twimg.com/profile_images/514549811765211136/9SgAuHeY.png',
      users:['1','2','3','4','5']
  }];
  var _messages = [{
      content: '你在路上吗?',
      timestamp: moment().subtract(1, 'hours').toDate(),
      user:{_id:'1',name:'李健'},
      state:1
    },{
      content: '我到了',
      timestamp: moment().subtract(2, 'hours').toDate(),
      user:{_id:'2',name:'刘萌'},
      state:1
    },{
      content: '天王盖地虎',
      timestamp: moment().subtract(1, 'days').toDate(),
      user:{_id:'3',name:'玳瑁'},
      state:1
    },{
      content: '小鸡炖蘑菇',
      timestamp: moment().subtract(2, 'hours').toDate(),
      user:{_id:'4',name:'林萧'},
      state:1
    },{
      content: ' WTF?',
      timestamp: moment().subtract(1, 'hours').toDate(),
      user:{_id:'1',name:'李健'},
      state:1
    },{
      content: '明天早上4点开会!',
      timestamp: moment().subtract(4, 'days').toDate(),
      user:{_id:'1',name:'李健'},
      state:1
    },{
      content: '即时通讯测试',
      timestamp: moment().subtract(1, 'hours').toDate(),
      user:{_id:'1',name:'李健'},
      state:1
    },{
      content: '老板 V5 !',
      timestamp: moment().subtract(4, 'days').toDate(),
      user:{_id:'2',name:'刘萌'},
      state:1
  }];
  _messages.forEach(m => Messages.insert(m));

  _chats.forEach(chat => {
    let message = Messages.findOne({ chat_id: { $exists: false } });
    chat.last_message = message;
    let chat_id = Chats.insert(chat);
    Messages.update(message._id, { $set: { chat_id: chat_id } });
  });
  let notice = Chats.findOne({ is_notice: true });
  let noticeMsg = Messages.find({ chat_id: { $exists: false } });
  noticeMsg.forEach(m => {
    notice.last_message = m;
    Messages.update(m._id, { $set: { chat_id: notice._id } });
  });
}
